﻿using AntdUI;
using Microsoft.EntityFrameworkCore.Query.Internal;
using Super.Admin.Assets.CustomControl;
using Super.Admin.Entities;
using Super.Admin.Global;
using Super.Admin.IServices;
using Super.Admin.Mappers;
using Super.Admin.Models.User;
using Super.Admin.Services;
using Super.Admin.Utils;
using Super.Admin.Utils.EventAggregator;
using Super.Admin.Utils.EventAggregator.EventType;
using Super.Admin.Utils.ThemeManager;
using Super.Admin.Views.Login;
using System.ComponentModel;
using System.Windows.Forms;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.StartPanel;
using Panel = AntdUI.Panel;

namespace Super.Admin.Views
{
    public partial class FrmLogin : Base.BaseForm
    {
        private readonly IUserService _userService;
        private readonly IUserOperateLogService _userOperateLogService;
        // 图片背景颜色
        private readonly string _imageBackColor = "125, 185, 209, 236";
        // 初始化需要的控件
        private UcLoginContent _ucLoginContent; // 登录内容控件
        private UcSuperTitle _ucLoginTitle; // 标题控件
        private UcLoginSetting _ucLoginSetting; // 设置控件
        private UcLoginImageArea _ucLoginImageArea; // 图片区域控件
        private GridPanel _gridMain; // 主网格面板
        private GridPanel _gridLeft; // 左侧网格面板
        private GridPanel _gridRight; // 右侧网格面板
        private GridPanel _gridCenter; // 中间网格面板
        private StackPanel _pnlLeft; // 左侧堆叠面板
        private StackPanel _pnlRight; // 右侧堆叠面板
        private StackPanel _pnlCenter; // 中间堆叠面板
        private VirtualPanel _virtualTop; // 顶部虚拟面板
        private VirtualPanel _virtualBottom; // 底部虚拟面板
        public UserBaseModel LocalUser { get; set; } = new UserBaseModel(); // 本地用户数据
        public FrmLogin(IUserService userService, IUserOperateLogService userOperateLogService)
        {
            InitializeComponent();
            InitializeControls(); // 初始化控件
            SetLoginLayout(ThemeSettingHelper.Instance.ThemeConfig.LayoutSettings.LoginLayout.LoginLayoutType); // 初始化布局
            this.Load += FrmLogin_Load;
            _userService = userService;
            _userOperateLogService = userOperateLogService;
        }

        private void FrmLogin_Load(object? sender, EventArgs e)
        {
            ReadLocalUser();
            Global.AppContext.Instance.EventTokenList.Add(EventAggregator.Default.Subscribe<LoginEvent>(DoLogin));
        }

        // 登录
        private void DoLogin(LoginEvent loginEvent)
        {
            if (loginEvent.Type == LoginEvent.LoginType.Register)
            {
                if (string.IsNullOrEmpty(loginEvent.UserName) || string.IsNullOrEmpty(loginEvent.Password))
                {
                    AntdUI.Message.error(this, "用户名或密码不能为空");
                    return;
                }
                try
                {
                    _userService.CreateUser(new UserEntity { UserName = loginEvent.UserName, Password = loginEvent.Password }, null);
                }
                catch (Exception ex)
                {
                    AntdUI.Message.error(this, ex.Message);
                    return;
                }
                AntdUI.Message.success(this, "注册成功，请返回登录");
                return;
            }
            try
            {
                UserEntity entity = _userService.Login(loginEvent.UserName, loginEvent.Password);
                if (_ucLoginContent.IsRememberPassword)
                {
                    SaveUserLocalInfoSetting(loginEvent.UserName, loginEvent.Password);
                }
                else
                {
                    if (LocalUser.UserName != loginEvent.UserName || LocalUser.Password != loginEvent.Password)
                    {
                        AntdUI.Modal.open(new AntdUI.Modal.Config(this, "提示", "是否要记住密码", AntdUI.TType.Warn)
                        {
                            OnOk = config =>
                            {
                                SaveUserLocalInfoSetting(loginEvent.UserName, loginEvent.Password);
                                return true;
                            },
                        });
                    }
                }
                _userOperateLogService.CreateUserOperateLog(entity.UserId, "登录成功", "", 0);
                AntdUI.Message.success(this, "登录成功");
                DialogResult = DialogResult.OK;
                Global.AppContext.Instance.LoginUserModel = entity.ToDetailModel(); // 获取登录用户信息
                base.Close();
            }
            catch (Exception ex)
            {
                AntdUI.Message.error(this, ex.Message);
                _userOperateLogService.CreateUserOperateLog(110, $"[{loginEvent.UserName}]企图登录：" + ex.Message, "", 0);
                return;
            }
        }

        /// <summary>
        /// 读取本地用户数据
        /// </summary>
        private void ReadLocalUser()
        {
            if (File.Exists(FilePath.LocalUserDataFilePath))
            {
                string json = File.ReadAllText(FilePath.LocalUserDataFilePath);
                LocalUser = JsonHelper.GetObjectFromJsonString<UserBaseModel>(json);
                _ucLoginContent.UserName = LocalUser.UserName;
                _ucLoginContent.Password = LocalUser.Password;
            }
        }

        #region 登录布局设置
        /// <summary>
        /// 初始化控件
        /// </summary>
        private void InitializeControls()
        {
            // 初始化核心控件
            // 登录内容控件
            _ucLoginContent = new UcLoginContent();
            _ucLoginContent.Dock = DockStyle.Fill;
            _ucLoginContent.PnlMain.Radius = 50;

            // 标题控件
            _ucLoginTitle = new UcSuperTitle();
            _ucLoginTitle.Dock = DockStyle.Fill;

            // 设置小工具控件
            _ucLoginSetting = new UcLoginSetting();
            _ucLoginSetting.Dock = DockStyle.Fill;
            _ucLoginSetting.BtnLoginLayout.SelectedValueChanged += BtnLoginLayout_SelectedValueChanged;

            // 图片区域控件
            _ucLoginImageArea = new UcLoginImageArea();
            _ucLoginImageArea.Dock = DockStyle.Fill;

            // 初始化容器
            // 主容器
            _gridMain = new GridPanel();
            _gridMain.Dock = DockStyle.Fill;
            _gridMain.BackColor = Color.Transparent;

            // 左侧
            _gridLeft = new GridPanel();
            _gridLeft.Dock = DockStyle.Fill;
            _gridLeft.BackColor = Color.Transparent;
            _pnlLeft = new StackPanel();
            _pnlLeft.Dock = DockStyle.Fill;
            _pnlLeft.Vertical = true;
            _pnlLeft.Radius = 5;
            _pnlLeft.BackColor = Color.Transparent;

            // 右侧
            _gridRight = new GridPanel();
            _gridRight.Dock = DockStyle.Fill;
            _gridRight.BackColor = Color.Transparent;
            _pnlRight = new StackPanel();
            _pnlRight.Dock = DockStyle.Fill;
            _pnlRight.Vertical = true;
            _pnlRight.Radius = 5;
            _pnlRight.BackColor = Color.Transparent;

            // 中间
            _gridCenter = new GridPanel();
            _gridCenter.Dock = DockStyle.Fill;
            _gridCenter.BackColor = Color.Transparent;
            _pnlCenter = new StackPanel();
            _pnlCenter.Dock = DockStyle.Fill;
            _pnlCenter.Vertical = true;
            _pnlCenter.Radius = 5;
            _pnlCenter.BackColor = Color.Transparent;
        }


        /// <summary>
        /// 设置登录布局
        /// </summary>
        /// <param name="layout"></param>
        public void SetLoginLayout(LoginLayoutType layout)
        {
            this.SuspendLayout();
            InitializeLoginLayout();
            switch (layout)
            {
                // 由于winform绘制是反着绘制 则添加反着添加
                case LoginLayoutType.Left:
                    SetLoginLayoutLeft();
                    break;
                case LoginLayoutType.Right:
                    SetLoginLayoutRight();
                    break;
                case LoginLayoutType.Center:
                    SetLoginLayoutCenter();
                    break;
            }
            this.ResumeLayout();
        }

        private void SetLoginLayoutCenter()
        {
            _gridMain.Span = "50% 650 50%";
            // 右侧
            _pnlRight.Controls.Add(_ucLoginSetting);
            _gridMain.Controls.Add(_pnlRight);
            // 中间
            _virtualBottom.Height = 200;
            _pnlCenter.Controls.Add(_virtualBottom);
            _pnlCenter.Controls.Add(_ucLoginContent);
            _virtualTop.Height = 135;
            _pnlCenter.Controls.Add(_virtualTop);
            _gridMain.Controls.Add(_pnlCenter);
            // 左侧
            _pnlLeft.Controls.Add(_ucLoginTitle);
            _gridMain.Controls.Add(_pnlLeft);
            _gridMain.BackExtend = _imageBackColor;
        }

        private void SetLoginLayoutRight()
        {
            _gridMain.Span = "100% 650";

            // 右侧
            _virtualBottom.Height = 200;
            _pnlRight.Controls.Add(_virtualBottom);
            _pnlRight.Controls.Add(_ucLoginContent);
            _virtualTop.Height = 80;
            _pnlRight.Controls.Add(_virtualTop);
            _pnlRight.Controls.Add(_ucLoginSetting);
            _pnlRight.BackExtend = null;
            _gridMain.Controls.Add(_pnlRight);

            // 左侧
            _pnlLeft.Controls.Add(_ucLoginImageArea);
            _pnlLeft.Controls.Add(_ucLoginTitle);
            _pnlLeft.BackExtend = _imageBackColor;
            _gridMain.Controls.Add(_pnlLeft);
        }

        private void SetLoginLayoutLeft()
        {
            _gridMain.Span = "650 100%";
            // 右侧
            _pnlRight.Controls.Add(_ucLoginImageArea);
            _pnlRight.Controls.Add(_ucLoginSetting);
            _pnlRight.BackExtend = _imageBackColor;
            _gridMain.Controls.Add(_pnlRight);

            // 左侧
            _virtualBottom.Height = 200;
            _pnlLeft.Controls.Add(_virtualBottom);
            _pnlLeft.Controls.Add(_ucLoginContent);
            _virtualTop.Height = 80;
            _pnlLeft.Controls.Add(_virtualTop);
            _pnlLeft.Controls.Add(_ucLoginTitle);
            _pnlLeft.BackExtend = null;
            _gridMain.Controls.Add(_pnlLeft);
        }

        private void InitializeLoginLayout()
        {
            this.Controls.Clear();
            _gridMain.Controls.Clear();
            _pnlLeft.Controls.Clear();
            _pnlRight.Controls.Clear();
            _pnlCenter.Controls.Clear();
            _gridLeft.Controls.Clear();
            _gridRight.Controls.Clear();
            _gridCenter.Controls.Clear();
            _virtualTop = GetVirtualPanel(DockStyle.Top);
            _virtualBottom = GetVirtualPanel(DockStyle.Bottom);
            _gridMain.BackExtend = "";
            _pnlRight.BackExtend = null;
            _pnlLeft.BackExtend = null;
            _gridMain.BackColor = Color.Transparent;
            _pnlRight.BackColor = Color.Transparent;
            _pnlLeft.BackColor = Color.Transparent;
            this.Controls.Add(_gridMain);
        }

        /// <summary>
        /// 占位面板
        /// </summary>
        /// <returns></returns>
        private VirtualPanel GetVirtualPanel(DockStyle dock)
        {
            return new VirtualPanel
            {
                Dock = dock,
                BackColor = Color.Transparent
            };
        }
        private void BtnLoginLayout_SelectedValueChanged(object sender, ObjectNEventArgs e)
        {
            if (_ucLoginSetting.BtnLoginLayout.SelectedValue != null)
            {
                ThemeSettingHelper.Instance.ThemeConfig.LayoutSettings.LoginLayout.LoginLayoutType = Enum.Parse<LoginLayoutType>(_ucLoginSetting.BtnLoginLayout.SelectedValue.ToString());
                SetLoginLayout(ThemeSettingHelper.Instance.ThemeConfig.LayoutSettings.LoginLayout.LoginLayoutType);
            }
            else
            {
                Growl.Warning("请选择一个有效的登录布局选项");
            }
        }
        #endregion

        /// <summary>
        /// 保存用户设置
        /// </summary>
        private void SaveUserLocalInfoSetting(string userName, string password)
            => JsonHelper.SaveObjectToJsonFile<UserBaseModel>(new UserBaseModel { UserName = userName, Password = password }, FilePath.LocalUserDataFilePath);
    }
}
